import CryptoJS from 'crypto-js'
import { customerHttp } from '@/utils/http'
import { getEnvironment } from './index'

function objToBase64(data: any) {
  const wordArray = CryptoJS.enc.Utf8.parse(JSON.stringify(data))
  const base64 = CryptoJS.enc.Base64url.stringify(wordArray, false)
  return base64
}

const getCode = async () => {
  return new Promise((resolve, reject) => {
    uni.login({
      success(result) {
        resolve(result.code)
      },
      fail(result) {
        reject(result)
      }
    })
  })
}

function guids() {
  const s = []
  const hexDigits = '0123456789abcdef'
  // eslint-disable-next-line no-plusplus
  for (let i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
  }
  s[14] = '4' // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01
  // eslint-disable-next-line no-multi-assign
  s[8] = s[13] = s[18] = s[23] = '-'

  const uuid = s.join('')
  return uuid
}

function getDistinctId() {
  const userInfo = JSON.parse(uni.getStorageSync('userInfo') || '{}')
  if (userInfo.sysUser) {
    return userInfo.sysUser.userId
  }
  return ''
}

function getUserAgent() {
  const systemInfo = wx.getSystemInfoSync()
  return systemInfo.system
}

/**
 * 订单轨迹
 *
 * @param data
 * @returns
 */
// eslint-disable-next-line consistent-return
export async function report(data: any) {
  try {
    // eslint-disable-next-line no-underscore-dangle
    const _deviceId = await getCode()
    const uuid = guids()
    const project = `ylz_${getEnvironment()}`
    const distinct_id = getDistinctId().replace(/"/g, '')
    const user_agent = getUserAgent()
    const userType = 'diyituanc'
    let product_name
    if (userType) {
      product_name = userType.name.replace('我是', '')
    }
    const params: any = {
      debug: true,
      app: '小程序-集鲜直采',
      domain_id: 'TENANT',
      project,
      session_id: '-1',
      uuid,
      distinct_id,
      time: Date.now(),
      type: 'track',
      event: 'click',
      product_name,
      properties: {
        name_zh: data.name_zh || '首页',
        from: '',
        tenant_id: uni.getStorageSync('tenant_id'),
        name: `${product_name}端-${data.name}`,
        user_agent,
        p__device_id: _deviceId,
        workstand_id: null
      }
    }
    // eslint-disable-next-line no-console
    console.log(params)
    return customerHttp.request({
      url: `https://dove.ops.yunlizhi.cn/hope?data=${objToBase64(params)}`,
      method: 'get'
    })
  } catch (e) {
    // eslint-disable-next-line no-console
    console.log('report')
    // eslint-disable-next-line no-console
    console.log(e)
  }
}
